(* e81a - For noForth c&v FR59xx vsn 200202ff, 12-bit analog to digital conversion

   code by Jeroen Hoekstra & Willem Ouwerkerk

   ADC on, sample time at 64 clocks

   ADC-clock/4, sample timer on, 12-bit resolution
    P1.0 = A0   = 00
    P1.1 = A1   = 01
    P1.2 = A2   = 02
    P1.4 = A4   = 04
    P1.5 = A5   = 05
    P3.0 = A12  = 0C
    P3.1 = A13  = 0D
    P3.2 = A14  = 0E

   12-bit ADC using internal ADC12 of MSP430FR5xxx
   Use P3.0 as analog input and P1.2 to P1.7 as LED output

   Lower voltages could use 1.2 to 2.5 Volt reference for a higher resolution
   REFCTL0 = 1B0 = 20 selects 2.5 Volt reference
*)

hex
v: extra definitions
\ Select reference voltage: 100 = 1.2V, 101 = 2V, 102 = 2.5V, 103 = 2.5V
value REF   \ 100 = Use REF for conversion, 0 = Use VCC as REF for conversion
: REF-ON    ( +n -- )
    dup 100 and  to ref             \ Use REF for ADC conversion
    begin  400 1B0 bit** 0= until   \ Wait if VREF=bit:10=busy - essential! avoids race-hazard
    3 and  10 *  1 or  1B0 !        \ Activate VREF at +n Volt
    begin  1000 1B0 bit** until ;   \ Wait till VREF is stable

: REF-OFF   ( -- )          0 to ref  1 1B0 **bic ; \ Deactivate VREF
: ADC-OFF   ( -- )          2 800 **bic  10 800 **bic  2 800 **bis ;

: ADC-ON    ( -- )
    FD 202 *bic             \ P1OUT      P1.2 to P1.7 are outputs
    FD 204 *bis             \ P1DIR      
    1 22A *bis              \ P3SEL0     P3.0 is analog in
    1 22C *bis              \ P3SEL1
    2 800 **bic             \ ADC12CTL0  Clear ENC, enable ADC register access
    4410 800 !              \ ADC12CTL0  Sampletime 64 clocks, ADC on
    2200 802 !              \ ADC12CTL1  Clock/4, use sample timer
    20 804 !                \ ADC12CTL2  12 bit resolution
    2 800 **bis             \ ADC12CTL0  Set ENC, lock ADC access
    ref-off ;               \ Use VCC as reference


\ We need to clear the ENC bit before setting a new input channel
\ ADC can be used with VCC and VREF (2.5V) as reference voltage
: ADC       ( +n -- +n )
    2 800 **bic             \ ADC12CTL0  Clear ENC
    1F and  ref or 820 !    \ ADC12MCTL0 Select input
    3 800 **bis             \ ADC12CTL0  Set ENC & ADC12SC
    begin 1 802 bit** 0= until \ ADC12CTL1  ADC12 busy?
    860 @ ;                 \ ADC12MEM0  Read result

: POT-ON    ( -- )          1 202 *bis ; \ Activate VCC to resistor
: POT-OFF   ( -- )          1 202 *bic ; \ Deactivate VCC to resistor
: >LEDS     ( +n -- )       6 rshift  2* 2*  3 or 202 ! ; \ Keep low 2-bits high


: LEDS      ( -- )          \ Show ADC outputs on 6 LEDs connected to P1.2 to P1.7
    base @ >r  decimal      \ Use decimal number conversion
    adc-on  pot-on          \ Initialise hardware
    begin
        0C adc  cr dup .  >leds  80 ms
    key? until  r> base !
    0 >leds ;

adc-on  v: fresh
' LEDS  to app
shield ADC\  freeze

\ End ;;;
